package main

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/plugins/cors"
	"github.com/beego/ms304-client/basis/conf"
	l "github.com/beego/ms304-client/basis/log"
	"github.com/beego/ms304-client/basis/socket"
	_ "github.com/beego/ms304-client/sysinit"
	"net/http"
)

var log = l.New("main")

func main() {

	h := func(w http.ResponseWriter, r *http.Request) {
		if origin := r.Header.Get("Origin"); origin != "" {
			log.Warn(origin)
			w.Header().Set("Access-Control-Allow-Origin", origin)
		} else {
			w.Header().Set("Access-Control-Allow-Origin", "*")
		}

		w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "X-HTTP-Method-Override, Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, X-Requested-With")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		// w.Header().Set("Access-Control-Max-Age", "86400")

		socket.Server.ServeHTTP(w, r)
	}

	// socket
	http.HandleFunc("/socket.io/", h)

	// http.Handle("/socket.io/", controllers.Server)

	go func() {
		if err := http.ListenAndServe(conf.String("socket_url"), nil); err != nil {
			panic(err)
		}
	}()

	// beego.SetStaticPath("/client", "client")
	beego.SetStaticPath("/admin", "./views/admin")

	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

	var FilterGateWay = func(ctx *context.Context) {
		ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "86400")
	}

	beego.InsertFilter("*", beego.BeforeRouter, FilterGateWay)

	beego.Run()
}
